﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Top.Api.Util;

namespace CloudTaobao.Util
{
    public class TOPClient
    {
        public const string APP_KEY = "app_key";
        public const string FORMAT = "format";
        public const string METHOD = "method";
        public const string TIMESTAMP = "timestamp";
        public const string VERSION = "v";
        public const string SIGN = "sign";
        public const string SIGN_METHOD = "sign_method";
        public const string PARTNER_ID = "partner_id";
        public const string SESSION = "session";
        public const string FORMAT_XML = "xml";
        public const string MD5 = "md5";
        public const string TTID = "ttid";

        //private const string serverUrl = "http://gw.api.tbsandbox.com/router/rest";
        private const string serverUrl = "http://gw.api.taobao.com/router/rest";
        private const string appKey = "12258862";
        //private const string appSecret = "sandbox06188e58800889532f557b8fe";
        private const string appSecret = "838101106188e58800889532f557b8fe";
        private const string ttid = "400000_12258862@yqft_windowsphone7_1.0.0";
        private const string format = FORMAT_XML;

        private Dictionary<string,string> txtParams = new Dictionary<string, string>();

        #region DefaultTopClient Constructors

        #endregion

        #region ITopClient Members

        public void addParameter(string key, string value)
        {
            if (key != null && !key.Equals("")) 
            {
                txtParams.Add(key, value);
            }
        }

        public Dictionary<string, string> getSortedDictionary(Dictionary<string, string> origin) 
        {
            Dictionary<string,string> dict = (from entry in origin orderby entry.Key ascending select entry).ToDictionary(x => x.Key, x => x.Value);
            return dict;
        }

        private string buildQuery(Dictionary<string, string> parameters)
        {
            string query = "";
            IEnumerator<KeyValuePair<string, string>> textEnum = parameters.GetEnumerator();
            while (textEnum.MoveNext())
            {
                query += textEnum.Current.Key;
                query += "=";
                query += textEnum.Current.Value;
                query += "&";
            }
            query = query.Substring(0, query.Length - 1);
            return query;
        }

        public void sendRequest(AsyncCallback callback)
        {
            if (!Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                throw new NetException();
            // 添加协议级请求参数
            txtParams.Add(VERSION, "2.0");
            txtParams.Add(APP_KEY, appKey);
            txtParams.Add(FORMAT, format);
            txtParams.Add(SIGN_METHOD, MD5);
            //txtParams.Add(PARTNER_ID, "top-sdk-net-20110512");
            txtParams.Add(TIMESTAMP, DateTime.Now.Millisecond.ToString());

            txtParams = getSortedDictionary(txtParams);
            // 添加签名参数
            txtParams.Add(SIGN, TopUtils.SignTopRequest(txtParams, appSecret));

            UriBuilder fullUri = new UriBuilder(serverUrl);

            //组装query字符串
            string query = buildQuery(txtParams);

            fullUri.Query = query;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUri.Uri);

            // set up the state object for the async request
            UpdateState state = new UpdateState();
            state.AsyncRequest = request;

            // start the asynchronous request
            request.BeginGetResponse(callback, state);

        }

        #endregion
    }

    /// <summary>
    /// State information for our BeginGetResponse async call
    /// </summary>
    public class UpdateState
    {
        public HttpWebRequest AsyncRequest { get; set; }
        public HttpWebResponse AsyncResponse { get; set; }
    }
}
